// Copyright (c) Google LLC 2019
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

#include <deque>
#include <string>
#include <vector>

#include "gtest/gtest.h"
#include "third_party/brotli/interface/brotli.h"
#include "../common/constants.h"
#include <brunsli/jpeg_data.h>
#include <brunsli/status.h>
#include <brunsli/types.h>
#include <brunsli/brunsli_decode.h>
#include <brunsli/jpeg_data_writer.h>
#include "../dec/state.h"
#include "./test_utils.h"

namespace brunsli {

using ::brunsli::internal::dec::State;

TEST(StreamDecodeTest, DoneDone) {
  std::vector<uint8_t> src = GetSmallBrunsliFile();

  JPEGData jpg;
  State state;
  state.data = src.data();
  state.len = src.size();
  state.pos = 0;

  uint8_t foo[] = {42};

  // Decoding is finished.
  ASSERT_EQ(BRUNSLI_OK, internal::dec::ProcessJpeg(&state, &jpg));
  ASSERT_EQ(src.size(), state.pos);

  // It is OK to "continue" decoding, result is still "OK"...

  ASSERT_EQ(BRUNSLI_OK, internal::dec::ProcessJpeg(&state, &jpg));

  // ... unless more data is added.
  state.data = foo;
  state.len = 1;
  state.pos = 0;
  ASSERT_EQ(BRUNSLI_INVALID_BRN, internal::dec::ProcessJpeg(&state, &jpg));
}

TEST(StreamDecodeTest, ErrorError) {
  std::vector<uint8_t> src = GetSmallBrunsliFile();

  JPEGData jpg;
  State state;
  state.data = src.data();
  state.len = src.size();

  // Once decoder detects corrupted input...
  uint8_t original = src[0];
  src[0] = 42;
  ASSERT_EQ(BRUNSLI_INVALID_BRN, internal::dec::ProcessJpeg(&state, &jpg));

  // ... passing fixed input does not switch decoder to a good state.
  src[0] = original;
  ASSERT_EQ(BRUNSLI_INVALID_BRN, internal::dec::ProcessJpeg(&state, &jpg));
}

TEST(StreamDecodeTest, BytewiseInput) {
  std::vector<uint8_t> src = GetSmallBrunsliFile();

  JPEGData jpg;
  State state;
  for (size_t start = 0; start < src.size(); ++start) {
    state.data = src.data() + start;
    state.pos = 0;
    state.len = 1;
    ASSERT_EQ(start + 1 < src.size() ? BRUNSLI_NOT_ENOUGH_DATA : BRUNSLI_OK,
              internal::dec::ProcessJpeg(&state, &jpg));
    ASSERT_EQ(1, state.pos) << start;
  }
}

// 1600x1600 baseline JPEG.
// Together Brunsli + Brotli give over 100x compression!
uint8_t kBrnBr[] = {
  0xd1, 0x70, 0xaa, 0xc0, 0x7f, 0x24, 0xc6, 0xb1, 0x90, 0x53, 0xb1, 0x72,
  0x14, 0x3c, 0x3c, 0x78, 0xe9, 0xaf, 0xc4, 0x81, 0x70, 0x30, 0xd8, 0xe9,
  0x15, 0x74, 0xb6, 0x77, 0x44, 0x93, 0xbb, 0xfd, 0x96, 0xa4, 0x59, 0x60,
  0x1c, 0x10, 0x84, 0x11, 0x3b, 0x78, 0x83, 0x58, 0xea, 0x26, 0xa2, 0x29,
  0x26, 0x40, 0xa5, 0x00, 0x04, 0x28, 0x70, 0x35, 0xd5, 0x6f, 0xff, 0x5b,
  0xe9, 0x6d, 0x6b, 0x6a, 0xfc, 0xd2, 0xdc, 0xba, 0x57, 0x9c, 0x75, 0xbd,
  0xf1, 0x3d, 0xc2, 0xdf, 0xd7, 0xd1, 0x6f, 0x67, 0x3d, 0xdc, 0xb0, 0xdd,
  0xd0, 0x96, 0x63, 0xba, 0xfd, 0x5c, 0xaf, 0xf7, 0x8f, 0x1c, 0xea, 0xb4,
  0x91, 0x5d, 0xb7, 0x76, 0x2d, 0x1d, 0x9a, 0x4c, 0xd5, 0x2e, 0xd7, 0x8a,
  0xca, 0x93, 0x25, 0x37, 0x6e, 0xac, 0x52, 0x2b, 0x84, 0x25, 0xea, 0x22,
  0x59, 0x18, 0x54, 0xf5, 0x7c, 0x4e, 0x55, 0xe1, 0xb5, 0x21, 0x9a, 0x02,
  0x35, 0xaa, 0x20, 0xaf, 0x42, 0xa9, 0x5d, 0x5d, 0x25, 0x0b, 0x8b, 0xd5,
  0xd8, 0x31, 0x79, 0x49, 0xb2, 0xaa, 0x3c, 0xab, 0xad, 0x79, 0x3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, 0x50, 0xde,
  0x68, 0xb0, 0x83, 0x6f, 0x11, 0x07, 0xd4, 0x05, 0x30, 0xc3, 0x11, 0xbc,
  0x0e, 0x30, 0x49, 0xc8, 0x4a, 0xa0, 0xff, 0xd7, 0x00, 0x6a, 0x57, 0x01,
  0x38, 0x37, 0x02, 0x3f, 0xa1, 0x1a, 0x13, 0x6c, 0x6d, 0x07, 0x16, 0x74,
  0x02, 0xac, 0xb1, 0x02, 0x64, 0x92, 0x80, 0x34, 0x71, 0x10, 0x88, 0x51,
  0x37, 0x60, 0xbd, 0x44, 0xb0, 0x82, 0x12, 0x64, 0xdf, 0x67, 0x00, 0x6c,
  0xb2, 0x04, 0xdf, 0xa1, 0x0a, 0x93, 0x78, 0x77, 0x01, 0x5a, 0xb8, 0x01,
  0xdc, 0xb0, 0x18, 0x68, 0x50, 0x25, 0x52, 0xa7, 0x0f, 0x88, 0xd7, 0xf5,
  0x05, 0x3e, 0x91, 0x82, 0x7c, 0x8e, 0x00, 0xf6, 0x5b, 0x83, 0x38, 0x6d,
  0x24, 0x88, 0xd4, 0x05, 0xa4, 0xfe, 0x48, 0xc0, 0xac, 0x37, 0x20, 0x5b,
  0x65, 0xe4, 0x1d, 0xdb, 0x01, 0x9d, 0xde, 0x0f, 0x16, 0xfa, 0x18, 0xf9,
  0xc8, 0xc5, 0x20, 0xfb, 0x02, 0x01, 0x0d, 0x5e, 0x0c, 0x2a, 0xc5, 0x22,
  0xae, 0xde, 0x01, 0xde, 0xbf, 0x14, 0xe9, 0x8c, 0x77, 0x60, 0x4f, 0xa2,
  0x90, 0x1f, 0x3d, 0x84, 0x3c, 0x37, 0x08, 0xc8, 0xa2, 0x10, 0x80, 0x55,
  0x07, 0x00, 0xbc, 0x97, 0x83, 0x4d, 0xbf, 0x05, 0xd0, 0x64, 0x0d, 0x40,
  0x7f, 0x3b, 0x20, 0x3f, 0x5d, 0x81, 0x36, 0x7c, 0x0a, 0x96, 0x94, 0x0c,
  0xd6, 0x28, 0x1f, 0xd9, 0x12, 0x7b, 0xe0, 0x4e, 0xd9, 0x20, 0xcf, 0xd3,
  0x80, 0x62, 0xb3, 0x11, 0x5f, 0x7e, 0x01, 0x50, 0xb8, 0x04, 0x64, 0xdf,
  0x5a, 0x80, 0x57, 0x1d, 0x00, 0xe3, 0x1f, 0x20, 0x2f, 0xa9, 0x0f, 0x6e,
  0x98, 0x83, 0x30, 0xa3, 0x35, 0xa0, 0x9b, 0x9b, 0x00, 0x0f, 0x7d, 0x00,
  0x9f, 0x59, 0x8b, 0x2c, 0xef, 0x21, 0xd8, 0xa7, 0x58, 0x84, 0x4b, 0xf5,
  0x80, 0x0c, 0x35, 0x06, 0xb8, 0xfc, 0x12, 0x50, 0xc2, 0x05, 0xe4, 0x1f,
  0xfb, 0x83, 0x09, 0xfb, 0x70, 0xfc, 0x26, 0x09
};

TEST(StreamDecodeTest, StreamingSerialization) {
  std::string br_bytes =
      std::string(reinterpret_cast<const char*>(kBrnBr), sizeof(kBrnBr));
  std::string brn_bytes;
  util::compression::Brotli decompressor;
  decompressor.Uncompress(br_bytes, &brn_bytes);
  const uint8_t* data = reinterpret_cast<uint8_t*>(brn_bytes.data());
  size_t size = brn_bytes.size();

  std::deque<size_t> output_chunk_size = {
    280,  // SOI, DHT, DQT, SOS
    16374, 16374, 16374, 10880  // Scan data; BitWriter bufer is 16KiB
  };

  BrunsliDecoder decoder;

  for (size_t start = 0; start < size; ++start) {
    size_t available_in = 1;
    const uint8_t* next_in = data + start;
    size_t available_out = 0;
    uint8_t out[1];
    uint8_t* next_out = out;
    BrunsliDecoder::Status result =
        decoder.Decode(&available_in, &next_in, &available_out, &next_out);
    ASSERT_TRUE(result != BrunsliDecoder::ERROR);

    size_t output_streak_len = 0;
    while (true) {
      available_in = 0;
      available_out = 1;
      next_out = out;
      result =
          decoder.Decode(&available_in, &next_in, &available_out, &next_out);
      if (available_out == 1) {
        ASSERT_TRUE((result == BrunsliDecoder::NEEDS_MORE_INPUT) ||
                    (result == BrunsliDecoder::DONE));
        break;
      } else {
        output_streak_len++;
        ASSERT_TRUE((result == BrunsliDecoder::NEEDS_MORE_OUTPUT) ||
                    (result == BrunsliDecoder::NEEDS_MORE_INPUT) ||
                    (result == BrunsliDecoder::DONE));
      }
    }
    if (output_streak_len != 0) {
      ASSERT_EQ(output_chunk_size[0], output_streak_len)
          << "idx: " << (5u - output_chunk_size.size());
      output_chunk_size.pop_front();
    }
  }
  ASSERT_TRUE(output_chunk_size.empty());
}

TEST(StreamDecodeTest, BytewiseFallbackInput) {
  std::vector<uint8_t> src = GetFallbackBrunsliFile();

  JPEGData jpg;
  State state;
  size_t start = 0;
  for (size_t end = 0; end < src.size(); ++end) {
    state.data = src.data() + start;
    state.pos = 0;
    state.len = end - start;
    ASSERT_EQ(BRUNSLI_NOT_ENOUGH_DATA,
              internal::dec::ProcessJpeg(&state, &jpg));
    start += state.pos;
  }
  state.data = src.data() + start;
  state.pos = 0;
  state.len = src.size() - start;
  ASSERT_EQ(BRUNSLI_OK, internal::dec::ProcessJpeg(&state, &jpg));
}
}  // namespace brunsli
